<?php
require_once("./secret.php");
$action = $_GET['action'];;
$name = $_GET['file'];
$file = decryptPhone('aes', $name);
$path = '/var/spool/asterisk/monitor/' . $file;
if (!file_exists($path)) {
    exit('录音文件不存在');
}
if ($action == 'down') {
    $filenamedis = date('Y-m-d-H-i-s') . strrchr($file, '.');
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Disposition: attachment; filename = " . $filenamedis);
    header("Content-Length: " . filesize($path));
    header("Content-Type: application/octet-stream");
    echo file_get_contents($path);
} else {
    $fileSize = filesize($path);
    $etag = md5(filemtime($path));
    $fp = fopen($path, 'rb');
    if (!$fp) {
        die('Could not open file');
    }
    $start = 0;
    $end = $fileSize - 1;
    if (isset($_SERVER['HTTP_RANGE']) && !empty($_SERVER['HTTP_RANGE'])) {
        //获取请求头中的Range字段
        $range = explode('-', substr($_SERVER['HTTP_RANGE'], strlen('bytes=')));

        $start = $range[0];
        if ($range[1] > 0) {
            $end = $range[1];
        }

        //构造断点续传响应头
        header('HTTP/1.1 206 Partial Content');
        header('Status: 206');
        header('Accept-Ranges: bytes');
        header('Content-Range: bytes ' . $start . '-' . $end . '/' . $fileSize);
        header('Content-Length: ' . ($end - $start + 1));
    } else {
        header('Content-Length: ' . $fileSize);
    }
    header('Content-Type: audio/mpeg');
    header('Last-Modified: ' . date('D, d M Y H:i:s \G\M\T', filemtime($file)));
    header('ETag: "' . $etag . '"');
    header('Expires: 0');
    if ($start > 0) {
        fseek($fp, $start); //移动文件指针
    }
    $bytesPosition = $start;
    while (!feof($fp) && $bytesPosition <= $end) {
        $chunk = 1024 * 1024 * 50; //每次读取50k
        if ($bytesPosition + $chunk > $end + 1) {
            $chunk = $end - $bytesPosition + 1;
        }
        $chunk = fread($fp, $chunk);
        if (!$chunk) {
            die('Could not read file');
        }
        print($chunk);
        flush();
        $bytesPosition += $chunk;
    }
    fclose($fp);
}
?>